/*
 * 标题:          农务数据库检索系统
 * 
 * 描述:  		  以mysql为数据库，远程连接数据库进行水稻、 小麦、昆虫等数据库的检索
 * 
 * 备注:			 demo开头的html、jsp和java文件均为测试用例，无实际效用
 *
 * Copyright (c) 2017, Nanjing Agricultural University, China
 */

package cn.edu.njau.ads.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 数据库连接工具类
 * 
 * @author zzy
 *
 */
public class DBUtil {
	
	//数据库用户名
	private static String user="zy"; 
	
	//密码   
	private static String password="123456"; 
	
	//数据库名  
	private static String db_rice="rice"; 
	private static String db_pest="pest";
	private static String db_cgris="cgris";
	
	//数据库连接字符串,编码为utf-8
	private static String url;

	
	/**
	 * 类加载时，执行此静态代码段,开启数据库连接Driver
	 */
	static{
		try {
			//加载驱动
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			System.out.println("the Driver failed to load !");
		}
	}
	
	/**
	 * 创建数据库连接
	 * 
	 * @return 创建连接成功，返回数据库连接对象；否则返回null
	 */
	public static Connection getConnection(String str){
		//连接类
		Connection conn = null;  
		if(str == "rice"){
			url = "jdbc:mysql://192.168.116.60/"+db_rice+"?useUnicode=true&amp;"+"characterEncoding=utf-8&useSSL=true";
			System.out.println("try to connect to the db rice.");
		}else if(str == "pest"){
			url = "jdbc:mysql://192.168.116.60/"+db_pest+"?useUnicode=true&amp;"+"characterEncoding=utf-8&useSSL=true";
			System.out.println("try to connect to the db pest.");		
		}else if(str == "cgris"){
			url = "jdbc:mysql://192.168.116.60/"+db_cgris+"?useUnicode=true&amp;"+"characterEncoding=utf-8&useSSL=true";
			System.out.println("try to connect to the db cgris.");
		}
		
		try {
			conn = DriverManager.getConnection(url,user,password);
			System.out.println("connect success!");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	/**
	 * 关闭数据库连接
	 * 
	 * @param Connection 数据库连接对象
	 */
	public static void closeConnection(Connection conn){
		try {
			if((conn != null)&&(! conn.isClosed())){
				conn.close();
				conn = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 关闭数据库查询指令
	 * 
	 * @param PreparedStatement 数据库查询指令
	 */
	public static void closeStatement(PreparedStatement pst){
		try {
			if ((pst != null) && (!pst.isClosed())) {
				pst.close();
				pst = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 关闭数据库查询结果集
	 * 
	 * @param ResultSet 数据库查询结果集
	 */
	public static void closeResultSet(ResultSet rs){
		try {
			if ((rs != null) && (!rs.isClosed())) {
				rs.close();
				rs = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
